﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Odyssey.Linq;
using SunTzu.Core.Data;

namespace Odyssey.Web.Controllers
{
    public class TopClassController : FrontBaseController
    {
        public ActionResult List(int? id)
        {
            BindMasterViewData(id);

            var subclasses = BindSubClass(id);

            BindSubclassArticles(subclasses);

            BindTopClass(id);

            return View();
        }

        private void BindTopClass(int? id)
        {
            var entity = id > 0
                 ? GetTable<tb_topclass>().FirstOrDefault(c => c.Id == id)
                 : new tb_topclass();
            ViewBag.TopClass = entity;
        }

        private void BindSubclassArticles(IOrderedQueryable<tb_subclass> subclasses)
        {
            var subclassIds = (from s in subclasses select s.Id).ToArray();
            var articles = GetTable<tb_article>()
                .Where(a => subclassIds.Contains(a.ClassId))
                .OrderBy(c => c.Id).ToArray();

            var subclassArticles = new Dictionary<tb_subclass, tb_article[]>();

            foreach (var subclass in subclasses)
            {
                subclassArticles.Add(subclass,
                    articles.Where(a => a.ClassId == subclass.Id)
                    .OrderByDescending(a => a.Id)
                    .Take(3).ToArray());
            }

            ViewBag.SubclassArticles = subclassArticles;
        }

        private IOrderedQueryable<tb_subclass> BindSubClass(int? id)
        {
            var subclasses = GetTable<tb_subclass>()
                .Where(c => c.TopClassId == id.GetValueOrDefault() && c.isnews == "N" && c.parentid == 0)
                .OrderBy(c => c.DisplayOrder);

            ViewData.Model = subclasses;
            return subclasses;
        }
    }
}
